package com.zhongxi.guoyuan.view.coinShopping;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.BaiduNaviManager.NaviInitListener;
import com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanListener;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.adapter.CommentAdapter;
import com.zhongxi.guoyuan.adapter.GvShopSlidingAdapter;
import com.zhongxi.guoyuan.adapter.coinShop.CoinCategoryAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.CoinGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.CoinGoodsResult;
import com.zhongxi.guoyuan.entity.coinStore.CoinShopDetailData;
import com.zhongxi.guoyuan.entity.coinStore.CoinShopDetailResult;
import com.zhongxi.guoyuan.entity.comment.CommentData;
import com.zhongxi.guoyuan.entity.comment.CommentResult;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CoinShoppingDetailActivity extends BaseActivity implements MyScrollView.OnScrollListener, View.OnClickListener {

    private LinearLayout scrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private MyScrollView myScrollView;
    private LinearLayout relaLayout;
    private boolean isMeasured;
    private int scrollHeight;
    private TextView tvGoHere;

    private PopupWindow popupWindow;
    private View popupWindow_view;

    private List<ProjectItemData> TITLES = new ArrayList<ProjectItemData>();
    private Spinner spinner;

    //地图导航
    private static final String APP_FOLDER_NAME = "Meirongyuan";
    private String mSDCardPath = null;
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    public static List<Activity> activityList = new LinkedList<Activity>();
    private boolean first;

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default :
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };
    private View view;
    private RelativeLayout relaComment;
    private RelativeLayout relaCommentTitle;
    private ImageView ivDismiss;
    private LinearLayout linearSelect;
    private NoScrollListView lvList;
    private TextView tvCheckstand;
    private NoScrollGridView gvList;
    private String shopid;
    private String type;
    private CoinShopDetailResult result;
//    private ImageView ivImg;
    private TextView tvStoreName;
    private RatingBar rb;
    private TextView tvScore;
    private TextView tvTime;
    private TextView tvView;
    private TextView tvDesc;
    private GvShopSlidingAdapter gvAdapter;
    private List<ProjectItemData> list = new ArrayList<ProjectItemData>();
    private int position = 0;
    private int orderid = 0;
    private CoinGoodsResult goodsResult;
    private NoScrollGridView gvGoodsList;
    private List<CoinGoodsData> data = new ArrayList<>();
    private CoinCategoryAdapter adapter;
    private boolean flag;
    private Button btCollection;
    private HorizontalScrollView hsView;
    private CommentAdapter commentAdapter;
    List<CommentData> commentData = new ArrayList<>();
    private Map<String, String> map = new HashMap<String, String>();
    private Button btShare;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;
    private LinearLayout linearBottom;
    private View popupWindowview;
    private PopupWindow popWindow;
    private ViewFlow mViewFlow;
    private BannerAdapter mBannerAdapter;

    private boolean refresh;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            scrollHeight = relaLayout.getBottom();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_coin_shopping);
        list.add(new ProjectItemData("0", "全部", ""));
        initTitle();
        tvTitle.setText("银币商家详情页");
        mShareAPI = UMShareAPI.get(this);
        shopid = getIntent().getStringExtra("shopid");
        tvGoHere = (TextView) findViewById(R.id.tvGoHere);
        relaComment = (RelativeLayout) findViewById(R.id.relaComment);
        view = (View) findViewById(R.id.view);

        tvStoreName = (TextView) findViewById(R.id.tvStoreName);
        tvScore = (TextView) findViewById(R.id.tvScore);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvView = (TextView) findViewById(R.id.tvView);
        tvDesc = (TextView) findViewById(R.id.tvSellCategory);
        rb = (RatingBar) findViewById(R.id.rb);
        spinner = (Spinner) findViewById(R.id.spinner);
        //收藏
        btCollection = (Button) findViewById(R.id.btCollection);
        btShare = (Button) findViewById(R.id.btShare);
        linearBottom = (LinearLayout) findViewById(R.id.linearBottom);

        //实现上拉布局悬停
        initScrollPause();

        relaCommentTitle = (RelativeLayout) findViewById(R.id.relaCommentTitle);
        linearSelect = (LinearLayout) findViewById(R.id.linearSelect);
        ivDismiss =(ImageView) findViewById(R.id.ivDismiss);

        gvList = (NoScrollGridView) findViewById(R.id.gvList);
        gvGoodsList =(NoScrollGridView) findViewById(R.id.gvGoodsList);

        lvList = (NoScrollListView) findViewById(R.id.lvList);
        tvCheckstand = (TextView) findViewById(R.id.tvCheckstand);
        hsView = (HorizontalScrollView) findViewById(R.id.hsView);

        order();

        //设置高度
        FrameLayout frame = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.detailRate, frame);
    }

    /**
     * 轮播
     * @param images
     */
    private void lunbo(List<String> images) {
        //初始化轮播控件
        mViewFlow = (ViewFlow) findViewById(R.id.viewflow);

        if(images.size()>0)
            mViewFlow.setSideBuffer(images.size()); // 实际图片数量
        if(mBannerAdapter == null){
            mBannerAdapter = new BannerAdapter(this, images);
            mViewFlow.setAdapter(mBannerAdapter);
        }else{
            mBannerAdapter.replaceAll(images);
        }
        mViewFlow.startAutoFlowTimer();
    }

    private void order() {
        //智能排序
        spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> spAdapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item);
        List<String> spList = new ArrayList<String>();
        spList.add("时间倒序");
        spList.add("价格正续");
        spList.add("价格倒序");
        spList.add("浏览量倒序");
        spAdapter.addAll(spList);
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spAdapter);
    }

    /**
     * 上拉悬停
     */
    private void initScrollPause() {
        /**
         * 上拉悬停
         */

        //滑动置顶
        scrollBody = (LinearLayout) findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
        myScrollView = (MyScrollView) findViewById(R.id.myScrollView);

        relaLayout = (LinearLayout) findViewById(R.id.relaLayout);
        /*ViewTreeObserver observer = relaLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if(!isMeasured){
                    scrollHeight = relaLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });*/
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new CoinCategoryAdapter(context, data);
        gvGoodsList.setAdapter(adapter);
        getStoreDetail();
    }

    /**
     * 获取店铺详情
     */
    private void getStoreDetail() {
        type = "details";
        String str = "&shopid="+shopid;
        getServer(Url.SHOP_DETAILS, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("details".equals(type)){
                result = gson.fromJson(response, CoinShopDetailResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                initShopData();
//                mapNavi();//初始化百度导航
            }else if("goods".equals(type)){
                goodsResult = gson.fromJson(response, CoinGoodsResult.class);
                if(pageNum==1){
                    data.clear();
                }
                if(null!=goodsResult.getGoodsInfo()&&goodsResult.getGoodsInfo().size()>0){
                    data.addAll(goodsResult.getGoodsInfo());
                }
                adapter.notifyDataSetChanged();
                flag = true;
            }else if("comments".equals(type)){
                CommentResult commentResult = gson.fromJson(response, CommentResult.class);
                if(pageNum ==1){
                    commentData.clear();
                }
                if(commentResult.getComments().size()>0){
                    commentData.addAll(commentResult.getComments());
                }
                try{
                    JSONObject obj = new JSONObject(response);
                    JSONObject userObj = obj.getJSONObject("user");
                    if(null!=userObj&&!"".equals(userObj)){
                        commentAdapter.setUser(userObj);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                commentAdapter.notifyDataSetChanged();
                flag = true;
            }else if("collection".equals(type)){
                BaseResponse res = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(res.getSafeobj());
                showShortToast("收藏成功！");
            }else if("shareget".equals(type)){
                ShareBeautifulResult result = gson.fromJson(response, ShareBeautifulResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showPopupWindow(result.getNum());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showPopupWindow(String num) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvTips.setText("成功分享获得"+num+"个美币");
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
            Gson gson = new Gson();
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if(null!=res.getSafeobj()&&!"".equals(res.getSafeobj())){
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            }
            if(1000==res.getCode()) {
                showShortToast("店铺已下架");
                finish();
            }else if(6206==res.getCode()){
                showShortToast("该项目已经收藏");
            }else if(1001==res.getCode()){
                showShortToast("用户未登录，请先登录");
            }
    }

    /**
     * 初始化店铺详情页面数据
     */
    private void initShopData() {
        try{
            if(null!=result.getShopInfo()&&!"".equals(result.getShopInfo())) {
                CoinShopDetailData info = result.getShopInfo();
                if(null!=info.getImages()&&info.getImages().size()>0&&!refresh)
                    lunbo(info.getImages());
                if (null != info.getName()&&!"".equals(info.getName())){
                    tvStoreName.setText(info.getName());
                }else{
                    tvStoreName.setText("");
                }
                if(null!=info.getWorktime()&&!"".equals(info.getWorktime())){
                    tvTime.setText(info.getWorktime()+"营业");
                }else{
                    tvTime.setText("**营业");
                }
                if(null!=info.getSubject()&&!"".equals(info.getSubject())){
                    tvDesc.setText("店面描述："+info.getSubject());
                }else{
                    tvDesc.setText("店面描述：");
                }
                if(null!=info.getViewnum()&&!"".equals(info.getViewnum())){
                    tvView.setText(info.getViewnum());
                }else{
                    tvView.setText("");
                }
                if(null!=info.getStarlevel()&&!"".equals(info.getStarlevel())){
                    rb.setRating(Float.parseFloat(info.getStarlevel()));
                    tvScore.setText(info.getStarlevel());
                }
                if(null!=result.getInnerCategory()&&result.getInnerCategory().size()>0&&!refresh){
                    list.addAll(result.getInnerCategory());
                    gvAdapter = new GvShopSlidingAdapter(context, list);
                    gvList.setAdapter(gvAdapter);
                    setGvParams(gvList, list, 4);
                    getGoods();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //设置gridView的属性
    private void setGvParams(NoScrollGridView gv, List list, int item) {
        int spaceWith = CommonTool.dip2px(context, 10);//左边距 paddingLeft
        int with = getResources().getDisplayMetrics().widthPixels / item;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(list.size() * with, LinearLayout.LayoutParams.WRAP_CONTENT);
        gv.setLayoutParams(params);
        gv.setColumnWidth(with - spaceWith);
        gv.setHorizontalSpacing(spaceWith);
        gv.setStretchMode(GridView.NO_STRETCH);   //不拉伸
        gv.setOverScrollMode(0);
        gv.setNumColumns(list.size());      //一排显示几列
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        myScrollView.setOnScrollListener(this);
        relaComment.setOnClickListener(this);
        ivDismiss.setOnClickListener(this);
        tvGoHere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindow();
            }
        });
        ivBack.setOnClickListener(this);
        tvCheckstand.setOnClickListener(this);
        btCollection.setOnClickListener(this);
        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
            }
        });
        gvGoodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(context, CoinGoodsActivity.class);
                intent.putExtra("goodsId", data.get(position).getId());
                startActivity(intent);
            }
        });
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long lon) {
                gvAdapter.setSelectIndex(pos);
                gvAdapter.notifyDataSetChanged();
                position = pos;
                pageNum = 1;
                getGoods();
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                orderid = position;
                pageNum = 1;
                flag = false;
                if(first)
                    getGoods();
                first = true;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 获取分类下的商品
     */
    private void getGoods() {
        try{
            type = "goods";
            String str = "&page="+pageNum+"&shopid="+shopid+"&innerCategory="+list.get(position).getId()+"&orderBy="+orderid;
            Log.i("base", str);
            getServer(Url.SHOP_GOODS_LIST, null, str, false, null, "get");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 弹出店面信息
     */
    private void getPopupWindow() {
        if (null != popWindow && popWindow.isShowing()) {
            popWindow.dismiss();
            return;
        } else {
            mapNavi();//初始化百度导航
            initPopupWindow();
        }
    }

    private void initPopupWindow() {
        popupWindowview = getLayoutInflater().inflate(R.layout.pop_store_info, null, false);
        popWindow = new PopupWindow(popupWindowview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindowview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupHeight = popupWindowview.getMeasuredHeight();
        int[] location = new int[2];
        linearBottom.getLocationOnScreen(location);
        popWindow.showAtLocation(linearBottom, Gravity.NO_GRAVITY, location[0], location[1] - popupHeight);

        ImageView ivCall = (ImageView) popupWindowview.findViewById(R.id.ivCall);
        ImageView ivMapNavi = (ImageView) popupWindowview.findViewById(R.id.ivMapNavi);
        TextView tvPhone = (TextView) popupWindowview.findViewById(R.id.tvPhone);
        TextView tvPosition = (TextView) popupWindowview.findViewById(R.id.tvPosition);
        TextView tvRailWay = (TextView) popupWindowview.findViewById(R.id.tvRailWay);
        TextView tvBus = (TextView) popupWindowview.findViewById(R.id.tvBus);

        if(null!=result.getShopInfo()&&!"".equals(result.getShopInfo())){
            CoinShopDetailData shopinfo = result.getShopInfo();
            if(null!=shopinfo.getPhone()&&!"".equals(shopinfo.getPhone())){
                tvPhone.setText(shopinfo.getPhone());
            }else{
                tvPhone.setText("");
            }
            if(null!=shopinfo.getAddress()&&!"".equals(shopinfo.getAddress())){
                tvPosition.setText(shopinfo.getAddress());
            }else{
                tvPosition.setText("");
            }
            if(null!=shopinfo.getTraffic()&&!"".equals(shopinfo.getTraffic())){
                tvRailWay.setText(shopinfo.getTraffic());
                tvBus.setText(shopinfo.getTraffic());
            }else{
                tvRailWay.setText("");
                tvBus.setText("");
            }
        }

        //打电话
        ivCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拨打电话
                Intent intent = new Intent(Intent.ACTION_DIAL);
                if(null!=result.getShopInfo().getPhone()){
                    Uri data = Uri.parse("tel:" + result.getShopInfo().getPhone());
                    intent.setData(data);
                    startActivity(intent);
                }
            }
        });

        //地图导航
        ivMapNavi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(BaiduNaviManager.isNaviInited()){
                    routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                }
            }
        });

        popupWindowview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(popWindow!=null&&popWindow.isShowing()){
                    popWindow.dismiss();
                    popWindow = null;
                }
                return false;
            }
        });
    }

    @Override
    public void onScroll(int scrollY) {
        if(scrollY >= scrollHeight){
            if(scrollBody.getParent() != linearStop){
                linearBegin.removeView(scrollBody);
                linearStop.addView(scrollBody);
            }
        }else{
            if(scrollBody.getParent() != linearBegin){
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (!MyTextUtils.isFastDoubleClick()&&flag) {
                pageNum++;
                if("goods".equals(type)){
                    getGoods();
                }else if("comments".equals(type)){
                    getComments();
                }
        }
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.ivBack:
                    finish();
                    break;
                case R.id.tvCheckstand:
                    Intent intent = new Intent(context, CoinCheckstandActivity.class);
                    intent.putExtra("shopid", shopid);
                    startActivity(intent);
                    break;
                case R.id.btCollection:
                    //收藏
                    getCollect();
                    break;
                case R.id.relaComment:
                    if (!MyTextUtils.isFastDoubleClick()) {
                        flag = false;
                        hsView.setVisibility(View.GONE);
                        gvGoodsList.setVisibility(View.GONE);
                        relaCommentTitle.setVisibility(View.VISIBLE);
                        lvList.setVisibility(View.VISIBLE);
                        linearSelect.setVisibility(View.GONE);
                        pageNum = 1;
                        getComments();
                    }
                    break;
                case R.id.ivDismiss:
                    pageNum = 1;
                    flag = false;
                    refresh = true;
                    hsView.setVisibility(View.VISIBLE);
                    gvGoodsList.setVisibility(View.VISIBLE);
                    relaCommentTitle.setVisibility(View.GONE);
                    lvList.setVisibility(View.GONE);
                    linearSelect.setVisibility(View.VISIBLE);
                    position = 0;
                    getStoreDetail();
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initPopuWindow() {
        {
            popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
            popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
            popupWindow.setFocusable(true);
            popupWindow.showAtLocation(btShare, Gravity.BOTTOM, 0, 0);
            TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
            LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
            LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
            LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
            LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
            View.OnClickListener shareClickListener = new View.OnClickListener(){

                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.ll_qq:
                            platform = SHARE_MEDIA.QQ;
                            break;
                        case R.id.ll_wechat:
                            platform = SHARE_MEDIA.WEIXIN;
                            break;
                        case R.id.ll_qzone:
                            platform = SHARE_MEDIA.QZONE;
                            break;
                        case R.id.ll_friendscircle:
                            platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                            break;
                    }
                    new ShareAction(CoinShoppingDetailActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("这家店铺不用现金，银币也能结账哦！")
                            .withText("推荐一个不用现金结账的好店铺："+result.getShopInfo().getName()+"，消费后银币就可结账哦！").withTargetUrl(Url.BASE_URL+"/share/silver/shopinfo?sid="+shopid)
                            .share();
                    popupWindow.dismiss();
                }
            };
            ll_qq.setOnClickListener(shareClickListener);
            ll_wechat.setOnClickListener(shareClickListener);
            ll_qzone.setOnClickListener(shareClickListener);
            ll_friendscircle.setOnClickListener(shareClickListener);
            tv_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
            type = "shareget";
            getServer(Url.SHARE, null, "", false, null, "get");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    private void getCollect() {
        if(!MyTextUtils.isFastDoubleClick()){
            type = "collection";
            map.clear();
            map.put("ftype","4");
            map.put("refid", shopid);
            getServer(Url.ADD_FAVORITE, map, "", false, null, "post");
        }
    }

    /**
     * 获取评论列表
     */
    private void getComments() {
        commentAdapter = new CommentAdapter(context, commentData);
        lvList.setAdapter(commentAdapter);
        type = "comments";
        String str = "&shopid="+shopid+"&page="+pageNum;
        getServer(Url.COIN_COMMENTS, null, str, false, null, "get");
    }

    private void mapNavi() {
        activityList.add(this);
        if (initDirs()) {
            initNavi();
        }
    }

    String authinfo = null;

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                CoinShoppingDetailActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        },  null, ttsHandler, ttsPlayStateListener);

    }

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(result.getShopInfo().getLongitude()), Double.parseDouble(result.getShopInfo().getDimensions()), "北京天安门", null, coType);
                break;
            }
            default:
                ;
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
			/*
			 * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "3");
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void initSetting(){
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    /**
     * 获取目录
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
